package redis

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/services/product/rpc/internal/config"
	"strconv"
	"time"
)

func InitRedis(conf *config.RedisConfig) (*redis.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	redisConfig := &redis.Options{
		Addr:     conf.Host + ":" + strconv.Itoa(conf.Port),
		Password: conf.Password,
		DB:       conf.DB,
		//在启动阶段创建指定数量的Idle连接，并长期维持idle状态的连接数不少于指定数量
		MinIdleConns: conf.MinIdleConns,
		// 读超时，默认3秒， -1表示取消读超时。
		ReadTimeout: time.Second * time.Duration(conf.ReadTimeout),
		// 写超时，默认等于读超时
		WriteTimeout: time.Second * time.Duration(conf.WriteTimeout),
		PoolSize:     conf.PoolSize,
		IdleTimeout:  time.Second * time.Duration(conf.IdleTimeout),
		MaxRetries:   conf.MaxRetries,
	}
	client := redis.NewClient(redisConfig)
	if cmd := client.Ping(ctx); cmd.Err() != nil {
		logx.Errorf("[InitRedis] 链接redis异常:%s", cmd.Err())
		return nil, cmd.Err()
	}
	return client, nil
}
